#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <ogcsys.h>
#include <fat.h>


#include "network.h"

/* Constants */
#define BLOCK_SIZE	1024

/* Macros */
#define round_up(x,n)	(-(-(x) & -(n)))

/* Variables */
static u8 titleBuf[BLOCK_SIZE] ATTRIBUTE_ALIGN(32);


s32 Title_ReadNetwork(const char *filename, void **out)
{
	void *buf = NULL;

	char netpath[ISFS_MAXPATH];
	s32 len, ret;

	/* Generate network path */
	sprintf(netpath, "/%s", filename);

	/* Request file */
	len = network_request(netpath);
	if (len < 0)
		return len;

	/* Allocate memory */
	buf = memalign(32, len);
	if (!buf)
		return -1;

	/* Download file */
	ret = network_read(buf, len);
	if (ret != len) {
		free(buf);
		return -2;
	}

	/* Set pointer */
	*out = buf;

	return len;
}

s32 Title_DownloadFile(const char *filename)
{

	//Variablen definieren
	char netpath[ISFS_MAXPATH];
    char filepath[ISFS_MAXPATH];
	u32 cnt, groesse, len;
	s32 ret;
	
	//SD Initializieren
	if(!fatInitDefault()){
		printf("Error:\nCannot initialize SD");
		return 0;
	}
	
	
	/* Generate network path */
	sprintf(netpath, "/%s", filename);

	/* Request file */
	len = network_request(netpath);
	
	groesse = len / 1024;
	printf("...%u KB", groesse);
	
	if (len < 0) {
        printf("\nRequest fehler.\n");
		return len;
	}

	// Ordner erstellen im moment nicht benoetigt
	// sprintf(ordner_pfad,"sd:/apps%s", downloadpfad);
    // mkdir(ordner_pfad, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);


    //Datei oeffnen

	FILE * fd;
    sprintf(filepath, "sd:/%s", filename);

	fd = fopen(filepath, "wb");

    //Datei schreiben

	for (cnt = 0; cnt < len; cnt += BLOCK_SIZE) {
		u32 blksize;

		/* Block size */
		blksize = (len - cnt);
		if (blksize > BLOCK_SIZE)
			blksize = BLOCK_SIZE;

		/* Read data */
		ret = network_read(titleBuf, blksize);
		if (ret != blksize) {
			ret = -1;
			printf("\nNetwork fehler.\n");
			fclose(fd);
			return ret;
		}

		fwrite(titleBuf,1,blksize, fd);

	}

	/* Success */
	ret = len;
	
	fclose(fd);
	return ret;
}
